﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Configuration;

namespace Ymatou.File.Lib
{
    public class ComponentLib
    {
        /// <summary>
        /// 将web页面转换为pdf
        /// </summary>
        /// <param name="url"></param>
        /// <param name="savePath"></param>
        public static void CreatePdfByHtml(string url, string savePath)
        {
            
            if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(savePath))
            {
                throw new ArgumentNullException();
            }

            string wkpdfPath = "wkhtmltopdf.exe";

            if(!string.IsNullOrEmpty(ConfigurationManager.AppSettings["WkhtmltopdfPath"]))
            {
                wkpdfPath = ConfigurationManager.AppSettings["WkhtmltopdfPath"];
            }

            //string options = "--print-media-type ";
            //options += "--redirect-delay 100 ";

            string folderPath = Path.GetDirectoryName(savePath);

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            if (System.IO.File.Exists(savePath))
            {
                System.IO.File.Delete(savePath);
            }
            try
            {
                Process process = new Process();
                process.StartInfo = new ProcessStartInfo()
                {
                    Arguments = url + " \"" + savePath + "\"",
                    CreateNoWindow = true,
                    FileName = wkpdfPath,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true
                };

                process.Start();

                //重定向，输入输出流
                string res = process.StandardOutput.ReadToEnd();
                string error = process.StandardError.ReadToEnd();

                process.WaitForExit(60000);
                int result = process.ExitCode;
                process.Close();

                if(result != 0)
                {
                    throw new Exception(string.Format(@"生成pdf失败:{0}\nurl:{3}\nStdOuput:\n{1}\nErrOutput:\n{2}", result, res, error, url));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}